package com.molichuxing.gateway.api.services.impl;


import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.DownloadFileUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.api.config.OptionalLogConfig;
import com.molichuxing.gateway.api.services.FinancialApiService;
import com.molichuxing.gateway.bff.dealer.entity.request.create.DealerEsignCreateVo;
import com.molichuxing.gateway.bff.dealer.services.DealerBffService;
import com.molichuxing.gateway.bff.financial.entity.request.create.EsignAccountCreateVo;
import com.molichuxing.gateway.bff.financial.entity.request.create.EsignCompanyCreateVo;
import com.molichuxing.gateway.bff.financial.entity.request.modify.InvoiceInfoModifyStatusVo;
import com.molichuxing.gateway.bff.financial.entity.request.modify.OfflineAuditModifyVo;
import com.molichuxing.gateway.bff.financial.entity.response.*;
import com.molichuxing.gateway.bff.financial.services.*;
import com.molichuxing.gateway.utils.ContantsUtil;
import com.molichuxing.gateway.utils.PoiExcelUtil;
import com.molichuxing.gateway.utils.TokenUtil;
import com.molichuxing.services.property.ContractTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 财务相关接口
 *
 * @author zhaopenghui
 * @date 2019年8月27日
 */
@Api(tags = "财务相关接口")
@RestController
@RequestMapping(value = "/financial")
public class FinancialApiServiceImpl extends RootApiService implements FinancialApiService {
    private static final Logger logger = LoggerFactory.getLogger(FinancialApiServiceImpl.class);

	@Resource
	private TokenUtil tokenUtil;

    @Resource
    StandingBookBffService standingBookBffService;
    @Resource
    OfflineAuditBffService offlineAuditBffService;
    @Resource
    ContractBffService contractBffService;
    @Resource
    InvoiceBffService invoiceBffService;
    @Resource
    DealerBffService dealerBffService;

	@Resource
	private FinancialDownloadBffService financialDownloadBffService;


    @Override
    @ApiOperation(value = "获取收款台账信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessType", value = "业务类型（1：订阅，2：专属）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "orderCode", value = "订单号", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "thirdPayNumber", value = "付款流水号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "userName", value = "用户账号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startPayTime", value = "付款开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endPayTime", value = "付款结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "payWay", value = "支付方式( 11：智能终端-微信， 12：智能终端-支付宝， 13：智能终端-pos机，14：智能终端-密码键盘，21：微信-H5， 22：微信-APP，23：微信-公众号，24：微信-扫码，25：微信-小程序，31：支付宝-H5，32：支付宝-APP，41: 线下支付，51：银联-H5，52：银联-APP)", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "payType", value = "支付类型（1：订购，3：加购，4：结算）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/ledger/receipt/list")
    public ResponseResult<Paged<ReceiptVo>> getReceiptPage(@RequestParam Map<String, Object> map,
                                                           @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        ResponseResult<Paged<ReceiptVo>> result = new ResponseResult<>();
        try {
            Integer businessType = ObjectCastUtil.castInteger(map.get("businessType"));
            if (null == businessType) {
                return result.error("业务类型不能为空");
            }

            return result.success(standingBookBffService.getReceiptPage(map, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getReceiptPage]获取收款台账信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getReceiptPage]获取收款台账信息异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getReceiptPage]获取收款台账信息异常", e);
            result.error("获取收款台账信息异常");
        }
        return result;
    }
    
	@Override
	@ApiOperation(value = "导出收款台账信息")
    @ApiImplicitParams({
			@ApiImplicitParam(name = "paymentIds", value = "支付单号ids(选择导出用)", required = false, dataType = "String"),
            @ApiImplicitParam(name = "businessType", value = "业务类型（1：订阅，2：专属）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "orderCode", value = "订单号", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "thirdPayNumber", value = "付款流水号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "userName", value = "用户账号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startPayTime", value = "付款开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endPayTime", value = "付款结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "payWay", value = "支付方式( 11：智能终端-微信， 12：智能终端-支付宝， 13：智能终端-pos机，14：智能终端-密码键盘，21：微信-H5， 22：微信-APP，23：微信-公众号，24：微信-扫码，25：微信-小程序，31：支付宝-H5，32：支付宝-APP，41: 线下支付，51：银联-H5，52：银联-APP)", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "payType", value = "支付类型（1：订购，3：加购，4：结算）", required = false, dataType = "Integer")
    })
	@GetMapping(value = "/download/ledger/receipt/list")
	public void receiptStandingBookDownload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> selectParams) {
		try {
            String fileName = null;
            Integer businessType = ObjectCastUtil.castInteger(selectParams.get("businessType"));
            if (businessType == null) {
                logger.error("[receiptStandingBookDownload]导出收款台账信息异常,业务类型不能为空");
            } else if (businessType == 1) {
                fileName = "订阅订单收款台账(" + DateUtil.formatDate(LocalDate.now()) + ").xlsx";
            } else if (businessType == 2) {
                fileName = "专属订单收款台账(" + DateUtil.formatDate(LocalDate.now()) + ").xlsx";
            } else {
                logger.error("[receiptStandingBookDownload]导出收款台账信息异常,业务类型({})错误", businessType);
            }
            List<ReceiptDownloadVo> datas = financialDownloadBffService.getReceiptStandingBookDownload(selectParams);

            // 生成excel
            XSSFWorkbook xssBook = PoiExcelUtil.receiptStandingBook(datas);
            // 下载
            DownloadFileUtil.downloadExcel(request, response, fileName, xssBook);
        } catch (BizException e) {
            logger.error("[receiptStandingBookDownload]导出收款台账信息异常:", e);
        } catch (Exception e) {
            logger.error("[receiptStandingBookDownload]导出收款台账信息异常:", e);
        }
	}

	@Override
	@ApiOperation(value = "导出收款台账信息查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "paymentIds", value = "支付单号ids(选择导出用)", required = false, dataType = "String"),
			@ApiImplicitParam(name = "businessType", value = "业务类型（1：订阅，2：专属）", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "orderCode", value = "订单号", required = false, dataType = "Long"),
			@ApiImplicitParam(name = "thirdPayNumber", value = "付款流水号", required = false, dataType = "String"),
			@ApiImplicitParam(name = "userName", value = "用户账号", required = false, dataType = "String"),
			@ApiImplicitParam(name = "startPayTime", value = "付款开始时间", required = false, dataType = "String"),
			@ApiImplicitParam(name = "endPayTime", value = "付款结束时间", required = false, dataType = "String"),
			@ApiImplicitParam(name = "payWay", value = "支付方式( 11：智能终端-微信， 12：智能终端-支付宝， 13：智能终端-pos机，14：智能终端-密码键盘，21：微信-H5， 22：微信-APP，23：微信-公众号，24：微信-扫码，25：微信-小程序，31：支付宝-H5，32：支付宝-APP，41: 线下支付，51：银联-H5，52：银联-APP)", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "payType", value = "支付类型（1：订购，3：加购，4：结算）", required = false, dataType = "Integer") })
	@GetMapping(value = "/download/ledger/receipt/list/query")
	public ResponseResult<Boolean> receiptStandingBookDownloadQuery(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Map<String, Object> selectParams) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			// 查询导出条数
			Long total = financialDownloadBffService.getReceiptStandingBookDownloadCount(selectParams);
			if (total != null && total > ContantsUtil.DOWNLOAD_EXCEL_MAX_NUM) {
				// 大于最大导出条数，异步发邮件
				financialDownloadBffService.getReceiptStandingBookDownloadEmail(selectParams, tokenUtil.getUser());
				// 返回提示
				result.success("已将导出数据发送至您的邮箱", true);
			} else {
				// 小于最大导出条数，提示前端调用直接导出接口
				result.success(false);
			}
		} catch (BizException e) {
			logger.error("[receiptStandingBookDownload]导出收款台账信息异常:", e);
			result.error("导出收款台账信息异常");
		} catch (Exception e) {
			logger.error("[receiptStandingBookDownload]导出收款台账信息异常:", e);
			result.error("导出收款台账信息异常");
		}

		return result;
	}

    @Override
    @ApiOperation(value = "获取经销商台账信息列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "thirdPayNumber", value = "付款流水号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "dealerId", value = "经销商id", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "startPayTime", value = "付款开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endPayTime", value = "付款结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")})
    @GetMapping(value = "/ledger/dealer/receipt/list")
    public ResponseResult<Paged<ReceiptVo>> getDealerReceiptPage(@RequestParam Map<String, Object> map,
                                                                 @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        ResponseResult<Paged<ReceiptVo>> result = new ResponseResult<>();
        try {
            return result.success(standingBookBffService.getDealerReceiptPage(map, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getDealerReceiptPage]获取经销商台账信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getDealerReceiptPage]获取经销商台账信息异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getDealerReceiptPage]获取经销商台账信息异常", e);
            result.error("获取经销商台账信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取保证金台账信息列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderCode", value = "订单号", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "thirdPayNumber", value = "付款流水号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "userName", value = "用户账号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startPayTime", value = "付款开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endPayTime", value = "付款结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "payWay", value = "支付方式( 11：智能终端-微信， 12：智能终端-支付宝， 13：智能终端-pos机，14：智能终端-密码键盘，21：微信-H5， 22：微信-APP，23：微信-公众号，24：微信-扫码，25：微信-小程序，31：支付宝-H5，32：支付宝-APP，41: 线下支付，51：银联-H5，52：银联-APP)", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")})
    @GetMapping(value = "/ledger/deposit/receipt/list")
    public ResponseResult<Paged<ReceiptVo>> getDepositReceiptPage(@RequestParam Map<String, Object> map,
                                                                  @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        ResponseResult<Paged<ReceiptVo>> result = new ResponseResult<>();
        try {
            return result.success(standingBookBffService.getDepositPage(map, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getDepositReceiptPage]获取保证金台账信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getDepositReceiptPage]获取保证金台账信息异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getDepositReceiptPage]获取保证金台账信息异常", e);
            result.error("获取保证金台账信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取还款审核信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "auditStatus", value = "审核状态（0：待审核，1：通过审核，2：驳回审核）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "serialNumber", value = "流水编号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "payName", value = "付款方", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startApplyTime", value = "提交开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endApplyTime", value = "提交结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/ledger/repay/check/list")
    public ResponseResult<Paged<OfflineInfoVo>> getOfflinePage(@RequestParam Map<String, Object> map,
                                                               @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<OfflineInfoVo>> result = new ResponseResult<>();
        try {
            modifyOfflineMap(map);
            if (null == pageNum || pageNum < 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize < 1) {
                pageSize = 10;
            }
            return result.success(offlineAuditBffService.getOfflinePage(map, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getOfflinePage]获取还款审核信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getOfflinePage]获取还款审核信息异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getOfflinePage]获取还款审核信息异常", e);
            result.error("获取还款审核信息异常");
        }
        return result;
    }

    /**
     * 日期转换
     *
     * @param map
     */
    private void modifyOfflineMap(Map<String, Object> map) {
        Object startApplyTime = map.get("startApplyTime");
        Object endApplyTime = map.get("endApplyTime");
        if (startApplyTime != null) {
            LocalDateTime dayStart = ObjectCastUtil.getDayStart(startApplyTime);
            map.put("startApplyTime", dayStart);
        }
        if (endApplyTime != null) {
            LocalDateTime dayEnd = ObjectCastUtil.getDayEnd(endApplyTime);
            map.put("endApplyTime", dayEnd);
        }
    }


    /**
     * 还款审核
     *
     * @param offlineAuditModifyVo
     * @return
     */
    @Override
    @ApiOperation(value = "还款审核")
    @PostMapping(value = "/ledger/repay/check/modify")
    @OptionalLogConfig(methods = "线下支付还款审核")
    public ResponseResult<Boolean> modifyAuditStatus(@RequestBody OfflineAuditModifyVo offlineAuditModifyVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(offlineAuditBffService.modifyAuditStatus(offlineAuditModifyVo));
        } catch (IllegalArgumentException e) {
            logger.error("[modifyAuditStatus]还款审核异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[modifyAuditStatus]还款审核异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyAuditStatus]还款审核异常", e);
            result.error("还款审核异常");
        }

        return result;
    }

    /**
     * 合同列表
     *
     * @param map
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @ApiOperation(value = "获取合同列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "contractStatus", value = "合同状态（1：生效中，2：自然失效，3：协商失效）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "businessType", value = "商品品类（1：订阅里程，2：专属里程）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "orderCode", value = "订单编号", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "contractCode", value = "合同编号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "realName", value = "用户名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startSignedTime", value = "签订开始日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endSignedTime", value = "签订结束日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startEndTime", value = "到期开始日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endEndTime", value = "到期结束日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/ledger/contract/main/list")
    public ResponseResult<Paged<ContractVo>> getMainContractPage(@RequestParam Map<String, Object> map,
                                                                 @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<ContractVo>> result = new ResponseResult<>();
        try {
            List<Integer> contractTypeList = new ArrayList<>();
            contractTypeList.add(ContractTypeEnum.COMMON_CONTRACT.getValue());
            contractTypeList.add(ContractTypeEnum.MILEAGE_BAG_CONTRACT.getValue());
            map.put("contractTypeList", contractTypeList);
            modifyContractTime(map);
            if (null == pageNum || pageNum < 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize < 1) {
                pageSize = 10;
            }
            return result.success(contractBffService.getContractPage(map, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getContractPage]获取合同列表异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getContractPage]获取合同列表异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getContractPage]获取合同列表异常", e);
            result.error("获取合同列表异常");
        }
        return result;
    }


    /**
     * 合同日期转换
     *
     * @param map
     */
    private void modifyContractTime(Map<String, Object> map) {
        Object startSignedTime = map.get("startSignedTime");
        Object endSignedTime = map.get("endSignedTime");
        Object startEndTime = map.get("startEndTime");
        Object endEndTime = map.get("endEndTime");

        if (startSignedTime != null) {
            LocalDateTime dayStart = ObjectCastUtil.getDayStart(startSignedTime);
            map.put("startSignedTime", dayStart);
        }
        if (endSignedTime != null) {
            LocalDateTime dayEnd = ObjectCastUtil.getDayEnd(endSignedTime);
            map.put("endSignedTime", dayEnd);
        }

        if (startEndTime != null) {
            LocalDateTime dayStart = ObjectCastUtil.getDayStart(startEndTime);
            map.put("startEndTime", dayStart);
        }
        if (endEndTime != null) {
            LocalDateTime dayEnd = ObjectCastUtil.getDayEnd(endEndTime);
            map.put("endEndTime", dayEnd);
        }
    }

    @Override
    @ApiOperation(value = "获取合同详情")
    @ApiImplicitParam(name = "mainOrderCode", value = "主合同订单编号", required = true, dataType = "Long")
    @GetMapping(value = "/ledger/contract/Sub/list")
    public ResponseResult<List<ContractVo>> getSubContractList(@RequestParam Long mainOrderCode) {
        ResponseResult<List<ContractVo>> result = new ResponseResult<>();
        try {
            return result.success(contractBffService.getSubContractList(mainOrderCode));
        } catch (IllegalArgumentException e) {
            logger.error("[getSubContractPage]获取合同详情异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getSubContractPage]获取合同详情异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getSubContractPage]获取合同详情异常", e);
            result.error("获取合同详情异常");
        }
        return result;
    }


    /**
     * 发票管理列表
     *
     * @param map
     * @param pageNum
     * @param pageSize
     * @return
     */

    @Override
    @ApiOperation(value = "获取发票管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "发票状态（0:待开票 1:已开票）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "orderCode", value = "订单编号", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "realName", value = "用户姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "businessType", value = "订单类型（1：订阅里程，2：专属里程）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "startApplyTime", value = "申请开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endApplyTime", value = "申请结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "invoiceTitleType", value = "'发票类型 1：个人 2：企业", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/invoice/list")
    public ResponseResult<Paged<InvoiceInfoVo>> getInvoiceInfoPage(@RequestParam Map<String, Object> map,
                                                                   @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<InvoiceInfoVo>> result = new ResponseResult<>();
        try {
            modifyInvoiceTime(map);
            if (null == pageNum || pageNum < 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize < 1) {
                pageSize = 10;
            }
            return result.success(invoiceBffService.getInvoiceInfoPage(map, pageNum, pageSize));
        } catch (BizException e) {
            logger.error("[getInvoiceInfoPage]获取发票管理列表异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getInvoiceInfoPage]获取发票管理列表异常", e);
            result.error("获取发票管理列表异常");
        }
        return result;
    }


    /**
     * 日期转换
     *
     * @param map
     */
    private void modifyInvoiceTime(Map<String, Object> map) {
        Object startApplyTime = map.get("startApplyTime");
        Object endApplyTime = map.get("endApplyTime");

        if (startApplyTime != null) {
            LocalDateTime dayStart = ObjectCastUtil.getDayStart(startApplyTime);
            map.put("startApplyTime", dayStart);
        }
        if (endApplyTime != null) {
            LocalDateTime dayEnd = ObjectCastUtil.getDayEnd(endApplyTime);
            map.put("endApplyTime", dayEnd);
        }
    }


    @Override
    @ApiOperation(value = "开票")
    @PostMapping(value = "/invoice/modify/status")
    @OptionalLogConfig(methods = "发票开票")
    public ResponseResult<Boolean> modifyInvoiceStatus(@RequestBody InvoiceInfoModifyStatusVo invoiceInfoModifyStatusVo) {

        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(invoiceBffService.modifyInvoiceStatus(invoiceInfoModifyStatusVo));
        } catch (BizException e) {
            logger.error("[modifyInvoiceStatus]开票异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyInvoiceStatus]开票异常", e);
            result.error("开票异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "合同日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "contractName", value = "合同名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "orderCode", value = "订单号", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "contractCode", value = "合同编号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "创建开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "创建结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/ledger/contract/log/list")
    public ResponseResult<Paged<ContractLogVo>> getMContractLogPage(@RequestParam Map<String, Object> map, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<ContractLogVo>> result = new ResponseResult<>();
        try {
            if (null == pageNum || pageNum < 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize < 1) {
                pageSize = 10;
            }
            return result.success(contractBffService.getInvoiceInfoPage(map, pageNum, pageSize));
        } catch (BizException e) {
            logger.error("[getMContractLogPage]合同日志列表异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getMContractLogPage]合同日志列表异常", e);
            result.error("合同日志列表异常");
        }
        return result;
    }

    /**
     * 创建经销商印章
     *
     * @param list
     * @return
     */
    @ApiIgnore
    @Override
    @ApiOperation(value = "创建经销商印章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dealerId", value = "经销商id", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "horizontalText", value = "横向文内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "upperChord", value = "上弦文内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "bottomChord", value = "下弦文内容", required = false, dataType = "String")
    })
    @PostMapping(value = "/dealer/esign/create")
    @OptionalLogConfig(methods = "创建经销商印章")
    public ResponseResult<Boolean> createDealerEsign(@RequestBody List<DealerEsignCreateVo> list) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            result.success(dealerBffService.createDealerEsign(list));
        } catch (BizException e) {
            logger.error("[createDealerEsign]创建经销商印章异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[createDealerEsign]创建经销商印章异常", e);
            result.error("创建经销商印章异常");
        }
        return result;
    }

    /**
     * 创建分子公司印章
     *
     * @param list
     * @return
     */
    @ApiIgnore
    @Override
    @ApiOperation(value = "创建分子公司印章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "fullName", value = "公司全称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "accountBank", value = "开户行", required = false, dataType = "String"),
            @ApiImplicitParam(name = "bankNumber", value = "对公账号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型（1：茉莉，2：资产公司）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "horizontalText", value = "横向文内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "upperChord", value = "上弦文内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "bottomChord", value = "下弦文内容", required = false, dataType = "String")
    })
    @PostMapping(value = "/company/esign/create")
    @OptionalLogConfig(methods = "创建分子公司印章")
    public ResponseResult<Boolean> createCompanyEsign(@RequestBody List<EsignCompanyCreateVo> list) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            result.success(contractBffService.createCompanyEsign(list));
        } catch (BizException e) {
            logger.error("[createCompanyEsign]创建分子公司印章异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[createCompanyEsign]创建分子公司印章异常", e);
            result.error("创建分子公司印章异常");
        }
        return result;
    }

    /**
     * 创建用户印章
     *
     * @param list
     * @return
     */
    @ApiIgnore
    @Override
    @ApiOperation(value = "创建用户印章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idNo", value = "用户身份证", required = false, dataType = "String"),
            @ApiImplicitParam(name = "mobile", value = "用户手机号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "用户姓名", required = false, dataType = "String"),
    })
    @PostMapping(value = "/account/esign/create")
    @OptionalLogConfig(methods = "创建用户印章")
    public ResponseResult<Boolean> createAccountEsign(@RequestBody List<EsignAccountCreateVo> list) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            result.success(contractBffService.createAccountEsign(list));
        } catch (BizException e) {
            logger.error("[createAccountEsign]创建用户印章异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[createAccountEsign]创建用户印章异常", e);
            result.error("创建用户印章异常");
        }
        return result;
    }

    @ApiIgnore
    @Override
    @ApiOperation(value = "初始化发票数据")
    @PostMapping(value = "/init/invoice/data")
    @OptionalLogConfig(methods = "初始化发票数据")
    public ResponseResult<Boolean> initInvoiceData() {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            result.success(invoiceBffService.initInvoiceData());
        } catch (BizException e) {
            logger.error("[initInvoiceData]初始化发票数据异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[createAccountEsign]初始化发票数据异常", e);
            result.error("初始化发票数据异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "企业订单合同编号是否存在")
    @GetMapping(value = "/contract/enterprise/exist")
    public ResponseResult<Boolean> getContractEnterpriseIsExist(@RequestParam String contractNo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            if (contractBffService.getContractEnterpriseIsExist(contractNo)) {
                // 存在
                result.error(ResponseCodeEnum.PARMS_ERROR.getCode(), "合同编号" + contractNo + "已存在，请输入正确合同编号");
            } else {
                // 不存在
                result.success(true);
            }
        } catch (BizException e) {
            logger.error("[getContractEnterpriseIsExist]查询企业订单合同编号是否存在异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getContractEnterpriseIsExist]查询企业订单合同编号是否存在异常", e);
            result.error("查询企业订单合同编号是否存在异常");
        }
        return result;
    }

}
